<template>
  <div class="submit-from">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item>
        <span class="title">{{ isRegister ? "账号注册" : "账户登录" }}</span>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          type="text"
          placeholder="用户名"
          required="required"
          v-model="ruleForm.username"
          prefix-icon="el-icon-user-solid"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          placeholder="密码"
          prefix-icon="el-icon-lock"
          v-model="ruleForm.password"
          @keyup.enter.native="toSubmitForm('ruleForm')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" v-if="isRegister">
        <el-input
          type="password"
          placeholder="确定密码"
          prefix-icon="el-icon-lock"
          v-model="ruleForm.confirmPassword"
          @keyup.enter.native="toSubmitForm('ruleForm')"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="isRegister" class="submit-btn">
        <el-button
          type="primary"
          @click="handleRegister('ruleForm')"
          style="width: 100%"
          >注册</el-button
        >
      </el-form-item>
      <el-form-item v-else class="submit-btn">
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          style="width: 100%"
          >登录</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-link
          class="link1"
          v-if="!isRegister"
          :underline="false"
          @click.native="isRegister = true"
          @click="handleRegister('ruleForm')"
          >注册用户</el-link
        >
        <el-link
          class="link2"
          v-else
          :underline="false"
          @click.native="isRegister = false"
          >返回</el-link
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss">
.submit-from {
  padding: 0 30px;
  .el-form-item__content {
    margin-left: 0px !important;
    .el-input__inner {
      border-radius: 0px;
    }
    .title {
      font-size: 20px;
      color: #666;
      margin-left: 100px;
    }
  }
  .submit-btn {
    margin-bottom: 0px;
  }
  .link1 {
    margin-left: 210px;
  }
  .link2 {
    margin-left: 230px;
  }
  .el-link:hover {
    color: red;
  }
  .el-button {
    margin-top: 50px;
    margin-bottom: 0px;
  }
}
</style>

<script>
import { login, register } from '../../api/user'
import { getStore } from '../../api/store'
import { setToken, setLoginInfo } from '../../utils/auth'
import getColor from '../../utils/txorbg'

export default {
  data () {
    const confirmPassword = (rule, value, callback) => {
      if (this.ruleForm.password !== value.toString() && this.isRegister) {
        callback(new Error('确认密码和新密码不一致！'))
      } else {
        callback()
      }
    }
    return {
      isRegister: false,
      ruleForm: {
        password: '',
        username: '',
        confirmPassword: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: ['blur']
          },
          {
            pattern: /^[0-9a-zA-Z_]{1,}$/,
            message: '用户名格式不正确，必须是字母数字或下划线',
            trigger: ['blur']
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: ['blur']
          }
        ],
        confirmPassword: [
          {
            required: true,
            message: '确定密码不能为空',
            trigger: ['blur']
          },
          { required: true, validator: confirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    isRegister () {
      this.ruleForm.password = ''
      this.ruleForm.username = ''
      this.ruleForm.confirmPassword = ''
    }
  },
  mounted () {
    // this.getUser()
  },
  methods: {
    // 获取登录用户信息
    async getUser () {
      const { data } = await getStore()
      console.log(data)
      this.$store.commit('setUserInfo', data.data)
      setLoginInfo(data.data)
      this.$router.push('/')
      setTimeout(() => {
        this.$router.go(0)
      }, 300)
    },
    // 登录
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.ruleForm)
            .then((res) => {
              if (res.data.code === 200) {
                // 添加token
                setToken(res.data.data.token)
                // 获取用户信息
                this.getUser()
              } else {
                this.$message.error(res.data.msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          console.log('error submit !!')
          return false
        }
      })
    },
    // 注册
    handleRegister (formName) {
      console.log(2222222222)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var newuser = this.ruleForm
          newuser.txcolor = getColor()
          newuser.bgcolor = getColor()
          console.log(newuser)
          register(newuser)
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success('注册成功')
                setTimeout(() => {
                  this.$router.push('/login')
                }, 300)
              } else {
                this.$message.error(res.data.msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          console.log('error register !!')
          return false
        }
      })
    }
  }
}
</script>
